var Router = require('koa-router')
var SysService = require('../../services/controllers/sys.ctrl')

function register(app) {
    var router = new Router({
        prefix: '/sys'
    });

    router.get('/', function *(next) {
        console.log(this.params.id, this.request.query, 'this is query!')
        var query = this.request.query;
        var finded = yield *SysService.findAndCountAll(this.paging,query);
        console.log(finded, 'lalala');
        this.body = RES.SUCCESS(finded,'success getdata', 200)
    }).get('/:id', function *(next) {
        console.log(this.params.id)
        var finded = yield *SysService.findAndCountAll(this.paging);
        console.log(finded, 'lalala');
        this.body = RES.SUCCESS(finded,'success getdata', 200)
    }).post('/', function *(next) {
        console.log('post here');
        var dt = this.request.body.dt;
        console.log(dt,'this is dt');
        var posted;
        try {
            posted = yield *SysService.create(dt);
        }catch (er) {
            console.log(er,'this is er');
            return this.body = RES.ERROR(er, posted, '创建用户失败', 500);
        }
        console.log('errored?')
        this.body = RES.SUCCESS(posted, 'success createSys', 200)

    }).put('/:id', function *(next) {
        console.log('put here', this.params.id);
        var dt = this.request.body.dt;
        console.log(dt,'this is dt');
        var puted;
        try {
            puted = yield *SysService.updateById(dt);
        }catch (er) {
            console.log(er,'this is er');
            return this.body = RES.ERROR(er, puted, '更新用户失败', 500);
        }
        this.body = RES.SUCCESS(puted, 'success updateSys', 200)

    }).delete('/:id', function *(next) {
        console.log('delete there');
        var params = this.params;
        var deleted;
        try {
            deleted = yield *SysService.deleteById(params);
        }catch (er) {
            console.log(er, 'this is er')
            return this.body = RES.ERROR(er, '删除用户失败', 500)
        }
        console.log('delete err?')
        this.body = RES.SUCCESS(deleted, 'success deleteSys', 200);
    })
    app.use(router.routes());
    app.use(router.allowedMethods());
}

module.exports = register;